package com.huisou.scheduler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;

import org.apache.commons.httpclient.HttpClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.handler.dataimport.DataImportHandlerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.huisou.dao.SaleDao;

public class RemoveIndexScheduler {
	
	private Properties							properties;
	
	private static final Logger					logger				= LoggerFactory.getLogger(RemoveIndexScheduler.class);
	
	@Resource
	private SaleDao								sd;
	private static final String					url					= "http://localhost:8070/";
	// private static final String url = "http://china.huisou.com/so/";
	
	private static final String					COMPANY_UPDATE_TIME	= "company.last_update_time";
	private static final String					SALE_UPDATE_TIME	= "sale.last_update_time";
	private static final String					NEWS_UPDATE_TIME	= "news.last_update_time";
	private static final String					ASK_UPDATE_TIME		= "ask.last_update_time";
	static final ThreadLocal<SimpleDateFormat>	DATE_TIME_FORMAT	= new ThreadLocal<SimpleDateFormat>() {
																		@Override
																		protected SimpleDateFormat initialValue() {
																			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
																		}
																	};
	
	public void run() {
		// removeSaleIndex();
		// removeCompanyIndex();
		// removeNewsIndex();
	}
	
	/**
	 * 删除已删除的产品信息索引
	 */
	public void removeSaleIndex() {
		try {
			loadProperties(false);
			HttpSolrServer server = getSolrServer("sale");
			Date now = new Date();
			String lastUpdate = (String) properties.get(SALE_UPDATE_TIME);
			if (lastUpdate == null)
				lastUpdate = "2012-08-20 10:55:27";
			List<String> ls = sd.queryDeleted(lastUpdate);
			if (ls != null && ls.size() > 0) {
				UpdateResponse ur = server.deleteById(ls);
				ur.getResponse();
				server.commit();
			}
			logger.error("已删除的产品信息个数为：{}", ls.size());
			properties.setProperty(SALE_UPDATE_TIME, DATE_TIME_FORMAT.get().format(now));
			persist(properties);
		}
		catch (SolrServerException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除已删除的公司信息索引
	 */
	public void removeCompanyIndex() {
		try {
			loadProperties(false);
			HttpSolrServer server = getSolrServer("company");
			Date now = new Date();
			String lastUpdate = (String) properties.get(COMPANY_UPDATE_TIME);
			if (lastUpdate == null)
				lastUpdate = "2010-01-01 10:55:27";
			List<String> ls = sd.queryCompanyDeleted(lastUpdate);
			if (ls != null && ls.size() > 0) {
				UpdateResponse ur = server.deleteById(ls);
				ur.getResponse();
				server.commit();
			}
			logger.debug("已删除的公司信息个数为：{}", ls.size());
			properties.setProperty(COMPANY_UPDATE_TIME, DATE_TIME_FORMAT.get().format(now));
			persist(properties);
		}
		catch (SolrServerException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 删除已删除的资讯信息索引
	 */
	public void removeNewsIndex() {
		try {
			loadProperties(false);
			HttpSolrServer server = getSolrServer("news");
			Date now = new Date();
			String lastUpdate = (String) properties.get(NEWS_UPDATE_TIME);
			if (lastUpdate == null)
				lastUpdate = "2010-01-01 10:55:27";
			List<String> ls = sd.queryNewsDeleted(lastUpdate);
			if (ls != null && ls.size() > 0) {
				UpdateResponse ur = server.deleteById(ls);
				ur.getResponse();
				server.commit();
			}
			logger.debug("已删除的资讯信息个数为：{}", ls.size());
			properties.setProperty(NEWS_UPDATE_TIME, DATE_TIME_FORMAT.get().format(now));
			persist(properties);
		}
		catch (SolrServerException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void removeSaleIndex(String id) {
		try {
			loadProperties(false);
			HttpSolrServer server = getSolrServer("sale");
			UpdateResponse ur = server.deleteById(Lists.newArrayList(id));
			ur.getResponse();
			server.commit();
		}
		catch (SolrServerException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private HttpSolrServer getSolrServer(String core) {
		HttpSolrServer server = null;
		try {
			server = new HttpSolrServer(url + core);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return server;
	}
	
	public static void main(String[] args) {
		RemoveIndexScheduler ris = new RemoveIndexScheduler();
		ris.removeSaleIndex("1061085");
	}
	
	public RemoveIndexScheduler() {
		loadProperties(true);
	}
	
	public void loadProperties(boolean force) {
		try {
			if (force || properties == null) {
				properties = new Properties();
				FileInputStream fis = new FileInputStream(getPropFile());
				properties.load(fis);
			}
		}
		catch (Exception e) {
			logger.error("读取索引更新属性文件失败", e);
		}
	}
	
	public SaleDao getSd() {
		return sd;
	}
	
	public void setSd(SaleDao sd) {
		this.sd = sd;
	}
	
	private void persist(Properties p) {
		OutputStream propOutput = null;
		try {
			propOutput = new FileOutputStream(getPropFile());
			properties.store(propOutput, null);
			logger.info("Wrote last indexed time to " + getPropFile());
		}
		catch (FileNotFoundException e) {
			throw new DataImportHandlerException(DataImportHandlerException.SEVERE, "Unable to persist Index Start Time", e);
		}
		catch (IOException e) {
			throw new DataImportHandlerException(DataImportHandlerException.SEVERE, "Unable to persist Index Start Time", e);
		}
		finally {
			try {
				if (propOutput != null)
					propOutput.close();
			}
			catch (IOException e) {
				propOutput = null;
			}
		}
	}
	
	private String getPropFile() {
		SolrResourceLoader loader = new SolrResourceLoader(null);
		logger.info("Instance dir = " + loader.getInstanceDir());
		String configDir = loader.getConfigDir();
		configDir = SolrResourceLoader.normalizeDir(configDir);
		
		String dataImportPropertiesPath = configDir + File.separator + "update.properties";
		
		return dataImportPropertiesPath;
	}
}
